package com.mspbots.sync.wise.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.sync.BaseGenericService;
import com.mspbots.sync.model.ExceptionLog;
import com.mspbots.sync.utils.WiseParamsUtils;
import com.mspbots.sync.wise.client.ClientProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Flux;

@Log4j2
@Service
@RequiredArgsConstructor
public class SlasService extends BaseGenericService {

    /**
     * get API Sals Data
     *
     * @param configuration slas config
     * @return get API Sals Data
     */
    public Flux<JsonNode> getSlas(ClientProperties configuration) {
        MultiValueMap<String, String> params = WiseParamsUtils.paginationBuild("1", null);
        return this.cwWebClient.fetch("/service/slas", params)
                .subscriberContext(ctx -> ctx.put("properties", configuration))
                .switchMap(jsonNode -> {
                    if (ObjectUtils.isEmpty(jsonNode.get("id"))) {
                        log.error("This tenant sync SLAS error.msg: {}", jsonNode);
                        this.messagingTemplate.convertAndSend("exception.log", ExceptionLog.builder()
                                .tenantId(configuration.getTenantId()).name("Connect wise")
                                .status(500).type("SYNC-WISE-SLAS").msg("Connect wise sync SLAS entry error.")
                                .extend(jsonNode).build());
                        return Flux.empty();
                    }
                    return Flux.just(jsonNode);
                });
    }

}
